package cn.dongqihong.framework.util;

import org.apache.log4j.Logger;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * Http请求工具
 * Created by DongQihong on 2016/6/2.
 */
public class HttpRequestUtil {
    /**
     * 日志记录者
     */
    private static Logger logger = Logger.getLogger(HttpRequestUtil.class);
    /**
     * UTF-8编码
     */
    public static final String CHARSET_UTF8 = "UTF-8";
    /**
     * GBK编码
     */
    public static final String CHARSET_GBK = "GBK";
    /**
     * GB2312编码
     */
    public static final String CHARSET_GB2312 = "GB2312";

    static String cookie = null;

    static Map cookieMap = new HashMap();

    /**
     * 发起get请求
     *
     * @param urlStr  请求的URL地址
     * @param charset 字符集
     * @param pretty  是否美化
     * @return 返回请求响应的HTML
     */
    public static String get(String urlStr, String charset, boolean pretty) {
        URL url;
        InputStream in = null;
        StringBuffer html = new StringBuffer();
        try {
            url = new URL(urlStr);
            in = url.openStream();
            BufferedReader bin = new BufferedReader(new InputStreamReader(in,
                    charset));
            String line;
            while ((line = bin.readLine()) != null) {
                if (pretty) {
                    html.append(line).append(
                            System.getProperty("line.separator"));
                } else {
                    html.append(line);
                }
            }
            in.close();
            bin.close();
        } catch (MalformedURLException e) {
            logger.warn(e.getMessage());
            return null;
        } catch (IOException e) {
            logger.warn(e.getMessage());
            return null;
        }
        return html.toString();
    }

    /**
     * 发起post请求
     *
     * @param url     请求的URL地址
     * @param params  请求参数
     * @param charset 字符集
     * @param pretty  是否美化
     * @return 返回请求响应的HTML
     */
    public static String post(String url, Map<String, String> params,
                              String charset, boolean pretty) {
        URL u = null;
        String paramString = null;
        HttpURLConnection con = null;
        // 构建请求参数
        StringBuffer sb = new StringBuffer();
        if (params != null) {
            for (Map.Entry<String, String> e : params.entrySet()) {
                sb.append(e.getKey());
                sb.append("=");
                sb.append(e.getValue());
                sb.append("&");
            }
            paramString = sb.substring(0, sb.length() - 1);
        }
        StringBuffer buffer = new StringBuffer();
        BufferedReader br = null;
        // 尝试发送请求
        try {
            u = new URL(url);
            con = (HttpURLConnection) u.openConnection();
            con.setRequestMethod("POST");
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setUseCaches(false);
            con.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            OutputStreamWriter osw = new OutputStreamWriter(
                    con.getOutputStream(), "UTF-8");
            osw.write(paramString);
            osw.flush();
            osw.close();
            // 读取返回内容
            br = new BufferedReader(new InputStreamReader(
                    con.getInputStream(), "UTF-8"));
            String temp;
            while ((temp = br.readLine()) != null) {
                buffer.append(temp);
                buffer.append("\n");
            }
            br.close();
        } catch (Exception e) {
            logger.warn(e.getMessage());
            return null;
        } finally {
            if (con != null) {
                con.disconnect();
            }
        }
        return buffer.toString();
    }

    private void gettingOrSettingCookie(HttpURLConnection httpURLConnection,
                                        boolean keepCookie) {
        // Getting or setting cookie.
        if (cookie == null || cookie.length() == 0) {
            String setCookie = httpURLConnection.getHeaderField("Set-Cookie");
            cookie = setCookie.substring(0, setCookie.indexOf(";"));
        } else if (keepCookie) {
            httpURLConnection.setRequestProperty("Cookie", cookie);
        }
    }

}
